<template>
	<!-- 线上充值 -->
	<view class="addCar OnlineRecharge">
		<u-navbar title="余额充值" title-color="#333" back-icon-color="#333"></u-navbar>
		<view class="OnlineRecharge-bottom">
			<view class="OnlineRecharge-content-box">
				<view class="Recharge-mode-font"> 充值金额 </view>
				<view class="OnlineRecharge-carName-phone OnlineRecharge-carName-renmb">
					¥
					<input class="OnlineRecharge-input-one" type="number" @blur="topMoneyChange"
						@input="rechargeMoneyUP" placeholder="请输入金额" v-model="rechargeMoney" maxlength="11" />
				</view>
				<view class="OnlineRecharge-carName-phone OnlineRecharge-carName-renmb">
					<input class="OnlineRecharge-input-one-phone" type="number" placeholder="请输入要充值的手机号"
						v-model="rechargeMoneyPhone" maxlength="11" />
				</view>
				<view class="OnlineRecharge-carName-tips">
					本次最多可充值¥20,000超过2万请联系
					<text class="OnlineRecharge-carName-zc">管理员</text>
				</view>
				<view class="OnlineRecharge-carName-zc" @click="youhui">查看优惠政策</view>
			</view>
			<view class="OnlineRecharge-content-box Recharge-mode">
				<view class="Recharge-mode-font">充值方式</view>
				<view class="OnlineRecharge-carName-phone Recharge-mode-top">
					<u-radio-group v-model="rechargeModeValue" :wrap="true" size="50"
						class="OnlineRecharge-radio-group">
						<u-radio v-for="(item, index) in RechargeModeList" :key="index" :name="item.name"
							:disabled="item.disabled">
							<image :src="item.url" mode="widthFix"></image>
							{{ item.name }}
						</u-radio>
					</u-radio-group>
				</view>
			</view>
			<view class="addCar-reset-determine">
				<view class="addCar-determine" @click="determine">
					<button style="border: none; color: #fff" plain="true" type="default">
						<view class="">
							<text>充值</text>
						</view>
					</button>
				</view>
				<view class="addCar-determine" style="background-color: #ff7f00">
					<button style="border: none; color: #fff" plain="true" type="default" @click="share">
						<view class="">
							<text>代充</text>
						</view>
					</button>
				</view>
			</view>
		</view>
		<u-modal v-model="addCarLoginShow" content="请确认是否充值" :show-cancel-button="true" @confirm="addCarConfirm">
		</u-modal>
		<u-modal v-model="addOuthWxLoginShow" content="请先进行微信授权" :show-cancel-button="true" @confirm="outhWx">
		</u-modal>
		<u-modal v-model="priceShow" content="订单支付成功" confirm-text="完成" @confirm="priceConfirm"></u-modal>
		<u-toast ref="uToast" />
		<!-- 银行支付验证码 -->
		<captcha-com ref="captchaCom" @captchaFinish="captchaFinish" :selectedPayment="selectedPayment"
			:paymentAmount="rechargeMoney"></captcha-com>
	</view>
</template>

<script>
import captchaCom from "./captcha-com.vue";
export default {
	components: {
		captchaCom,
	},
	data() {
		return {
			userinfo: JSON.parse(uni.getStorageSync("userinfo")),
			rechargeMoney: "", //充值金额
			addCarLoginShow: false,
			addOuthWxLoginShow: false,
			RechargeModeList: [
				{
					name: "微信",
					url: "../../static/images/WX.png",
					disabled: false,
				},
				{
					name: "支付宝",
					url: "../../static/images/ZFB.png",
					disabled: false,
				},
			],
			// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
			rechargeModeValue: "支付宝",
			rechargeMoneyPhone: "",
			resultData: "",
			priceShow: false,
			querywayInfoindex: 1,
			selectedPayment: null,
			merchant_order_num: "",
			payisChannel: 1, //支付方式
		};
	},
	onLoad() {
		this.rechargeMoneyPhone = this.userinfo.ORMTB410CA02;
		this.payGetProp();
	},
	methods: {
		/* 银行卡支付 */
		async bankPay() {
			uni.showLoading({
				title: "正在加载",
				mask: true,
			});
			this.selectedPayment = {
				title: this.rechargeModeValue,
			};
			let bid = this.RechargeModeList.find(
				(em) => em.name === this.rechargeModeValue
			).bid;
			// console.log(bid)
			let [err, res] = await uni.request({
				url: this.baseUrl + "/web/bank/put",
				method: "POST",
				dataType: "json",
				data: {
					ORMTB422CA00: "CUS",
					ORMTB422CA01: this.userinfo.ORMTB410ID,
					ORMTB422CA02: this.userinfo.PERTB005CA02,
					ORMTB422CA03: this.rechargeMoney,
					ORMTB422CA04: "银行卡",
					bid, // 银行卡绑id,
					remarks: "银行卡充值",
				},
			});
			uni.hideLoading();
			if (res && res.data.code === 0) {
				this.merchant_order_num = res.data.data;
				this.$refs.captchaCom.open();
			}
		},
		/* 	银行卡验证码输入 */
		async captchaFinish(kaptchaCode) {
			uni.showLoading({
				title: "请稍候...",
				mask: true,
			});
			let merchant_order_num = this.merchant_order_num;
			let [err, res] = await uni.request({
				url: this.baseUrl + "/web/bank/bankPay",
				method: "POST",
				dataType: "json",
				data: {
					merchant_order_num: this.merchant_order_num,
					code: kaptchaCode,
				},
			});
			uni.hideLoading();
			this.$refs.captchaCom.close();
			if (res.data.code === 0) {
				uni.showModal({
					content: "充值成功",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack();
						}
					},
				});
			}
		},
		async getBankList() {
			let [err, res] = await uni.request({
				url: this.baseUrl + "/web/bank/list",
				method: "POST",
				dataType: "json",
				data: {
					ormtb410id: this.userinfo.ORMTB410ID, //二级客户ID
				},
			});
			if (res.data.code === 0) {
				let list = res.data.data;
				list.forEach((item) => {
					let name = item.bankName + item.cardNo.substr(-4);
					this.RechargeModeList.push({
						name,
						url: item.bankImage,
						disabled: false,
						bid: item.bid,
					});
				});
			}
		},
		share() {
			if (this.rechargeMoney == 0)
				return uni.showToast({
					title: "请重新输入充值金额",
					duration: 5000,
					icon: "none",
				});
			if (this.rechargeMoneyPhone == "")
				return uni.showToast({
					title: "请输入要充值的手机号",
					duration: 5000,
					icon: "none",
				});
			let param = {};
			if (this.rechargeModeValue == "微信") {
				param = {
					type: 5,
					miniProgram: {
						id: "gh_fa047443538a",
						path: `pages/userPay/index?payPhone=${this.rechargeMoneyPhone}&payMore=${this.rechargeMoney}&payisChannel=${this.payisChannel}`,
						type: 0, //0-正式版；1-测试版；2-体验版。默认值0
						webUrl: "https://feishazoushi.cn/gw/",
					},
				};
				console.log(11111111, param);
				uni.share({
					provider: "weixin",
					scene: "WXSceneSession",
					imageUrl: "https://feishazoushi.cn/appImages/logo.png",
					title: "Hi~请帮我充值",
					...param,
					success: function (ret) {
						console.log("share success", JSON.stringify(ret));
					},
					fail: function (fail) {
						console.log(fail);
					},
				});
			} else if (this.rechargeModeValue == "支付宝") {
				//生成链接
				// param = {
				// 	type: 0,
				// 	summary: `¥ ${this.rechargeMoney}元`,  //描述
				// 	href: `https://feishazoushi.cn/alpay?payPhone=${this.rechargeMoneyPhone}&payMore=${this.rechargeMoney}&payisChannel=${this.payisChannel}&id=${this.userinfo.ORMTB410ID}&type=ZFB`,
				// };
				console.log(1111111111111, param.href);
				this.PayFunData()
			}

		},
		// 启动支付宝支付
		PayFunData() {
			var rechargeMoney = Number(this.rechargeMoney);
			let param = {
				ORMTB422CA01: this.userinfo.ORMTB410ID,
				ORMTB422CA03: rechargeMoney,
				ORMTB422CA11: this.rechargeMoneyPhone,
				ORMTB422CA13: "alipay",
			};

			uni.request({
				url: this.baseUrl + "/pay/czPayZY",
				method: "POST",
				dataType: "json",
				data: { ...param },
				success: (res) => {
					console.log("res", res);
					uni.hideLoading();
					if (res.data.code == 200) {
						let payObj = JSON.parse(res.data.data);
						console.log("payObj", payObj);
						uni.navigateTo({
							url: `/pages/shouquan/daifu/shareZFB?url=${payObj.alipay_token_id}`
						})
					} else {
						this.$refs.uToast.show({
							title: res.data.message,
							type: "default",
							icon: false,
						});
					}
				},
				fail: (res) => {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: res.errMsg,
						type: "default",
						icon: false,
					});
				},
			});
		},
		addCarConfirm() {
			let val =
				this.rechargeModeValue == "支付宝" || this.rechargeModeValue == "微信";
			if (!val) {
				this.bankPay();
				return;
			}
			var that = this;
			var rechargeMoney = Number(this.rechargeMoney);
			if (this.rechargeModeValue == "微信") {
				plus.share.getServices(
					function (res) {
						let sweixin = null;
						for (var i = 0; i < res.length; i++) {
							// console.log(res)
							var t = res[i];
							if (t.id == "weixin") {
								sweixin = t;
							}
						}
						//唤醒微信小程序
						if (sweixin) {
							sweixin.launchMiniProgram(
								{
									// 微信小程序的ID
									id: "gh_fa047443538a", //原始ID
									path: `/pages/payWeixin/index?moner=${rechargeMoney}&id=${that.userinfo.ORMTB410ID}&phone=${that.rechargeMoneyPhone}&payisChannel=${that.payisChannel}`, //跳转的小程序页面位置
									type: 0, //0-正式版； 1-测试版； 2-体验版
								},
								(res2) => {
									console.log(typeof res2, res2);
									// res2是微信小程序传递回来的参数 类型为string 需转化为json对象使用
									let result = JSON.parse(res2);
									console.log(result);
									// 拿到参数后执行你需要的逻辑
								},
								(err2) => {
									console.log(err2);
								}
							);
						} else {
							// 没有获取到微信分享服务
							uni.showToast({
								icon: "none",
								title: "当前环境不支持微信操作!",
							});
						}
					},
					function (e) {
						// console.log('获取分享服务列表失败：' + e.message);
					}
				);
			} else if (this.rechargeModeValue == "支付宝") {
				if (this.payisChannel == 2) {
					this.PayFunData();
				} else {
					let alipayUrl = `https://feishazoushi.cn/alih5?moner=${rechargeMoney}&phone=${that.rechargeMoneyPhone}`;
					// let alipayUrl = `https://feishazoushi.cn/alih5?moner=${rechargeMoney}&phone=${that.rechargeMoneyPhone}`;
					console.log("alipayUrl", alipayUrl);

					plus.runtime.openURL(
						"alipays://platformapi/startapp?appId=20000042&publicBizType=LIFE_APP&publicId=2021004106650137&url=" +
						encodeURIComponent(alipayUrl),
						function (res) {
							console.log(res);
						}
					);
				}
			}
		},
		// 启动支付宝支付
		PayFunData() {
			var rechargeMoney = Number(this.rechargeMoney);
			let param = {
				ORMTB422CA01: this.userinfo.ORMTB410ID,
				ORMTB422CA03: rechargeMoney,
				ORMTB422CA11: this.rechargeMoneyPhone,
				ORMTB422CA13: "alipay",
			};

			uni.request({
				url: this.baseUrl + "/pay/czPayZY",
				method: "POST",
				dataType: "json",
				data: { ...param },
				success: (res) => {
					console.log("res", res);
					uni.hideLoading();
					if (res.data.code == 200) {
						let payObj = JSON.parse(res.data.data);
						console.log("payObj", payObj);
						let url = encodeURIComponent(payObj.alipay_token_id)
						uni.navigateTo({
							url: `/pages/accountOnlineRecharge/webView?url=${url}`
						})
					} else {
						this.$refs.uToast.show({
							title: res.data.message,
							type: "default",
							icon: false,
						});
					}
				},
				fail: (res) => {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: res.errMsg,
						type: "default",
						icon: false,
					});
				},
			});
		},
		payGetProp() {
			uni.showLoading({
				title: "加载中...",
				mask: true,
			});
			uni.request({
				url: this.baseUrl + "/pay/getProp",
				method: "POST",
				dataType: "json",
				data: { ORMTB410ID: this.userinfo.ORMTB410ID },
				success: (res) => {
					uni.hideLoading();
					console.log(res.data);
					if (res.data.code == 200) {
						this.payisChannel = res.data.data;
					} else {
						this.$refs.uToast.show({
							title: res.data.message,
							type: "default",
							icon: false,
						});
					}
				},
				fail: (res) => {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: res.errMsg,
						type: "default",
						icon: false,
					});
				},
			});
		},
		// 确定
		determine() {
			if (this.rechargeMoney == 0)
				return uni.showToast({
					title: "请重新输入充值金额",
					duration: 5000,
					icon: "none",
				});
			if (this.rechargeMoneyPhone == "")
				return uni.showToast({
					title: "请输入要充值的手机号",
					duration: 5000,
					icon: "none",
				});
			this.addCarLoginShow = true;
		},
		rechargeMoneyUP() {
			var value = this.rechargeMoney;
			var num = this.clearNoNum(value);
			if (num > 20000.0) {
				uni.showToast({
					title: "充值金额高于最大限制20000.00",
					duration: 5000,
					icon: "none",
				});
			}
			num = num > 20000.0 ? 20000.0 : num;
			this.$nextTick(() => {
				this.rechargeMoney = num;
			});
		},
		topMoneyChange() {
			//充值金额失去焦点数据处理
			this.rechargeMoney = Number(this.rechargeMoney);
		},
		async outhWx() {
			let that = this; //保存当前作用域
			await uni.login({
				//直接用这个调用微信接口
				onlyAuthorize: true,
				provider: "weixin",
				success: function (response) {
					// 用微信登录的话就要去微信开发工具
					// console.log(response) //这里打印就说明接口调用成功了，然后看message login ：ok
					//微信登录就完了，后面就是获取用户信息
					uni.request({
						url: that.baseUrl + "/system/getOpenId/",
						method: "POST",
						dataType: "json",
						data: {
							code: response.code,
						},
						success(response) {
							// console.log(response)
							if (response.errMsg == "request:ok") {
								uni.setStorageSync("openid", that.openid);
							}
						},
					});
				},
			});
		},
		youhui() {
			uni.navigateTo({
				url: "../accountFavouredPolicy/index",
			});
		},
		clearNoNum(value) {
			value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
			value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
			value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
			value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
			if (value.indexOf(".") < 0 && value != "") {
				//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
				value = parseFloat(value);
			}
			return value;
		},
		priceConfirm() {
			this.resultData = "";
			uni.reLaunch({
				url: "/pages/myaccount/index",
			});
		},
		querywayInfo() {
			if (this.resultData == "") {
				return;
			}
			if (this.querywayInfoindex == 1) {
				uni.showLoading({
					title: "处理中...",
					mask: true,
				});
			}
			uni.request({
				url: this.baseUrl + "/pay/queryResultById",
				method: "POST",
				dataType: "json",
				data: {
					ORMTB422ID: this.resultData.order_no,
				},
				success: (res) => {
					uni.hideLoading();
					console.log(res);
					if (res.data.code == 200) {
						var data = res.data.data;
						if (data == 1) {
							if (this.querywayInfoindex == 1) {
								this.$refs.uToast.show({
									title: "订单支付未完成",
									type: "default",
									icon: false,
								});
							}
							if (this.querywayInfoindex < 5) {
								setTimeout(() => {
									this.querywayInfoindex += 1;
									this.querywayInfo();
								}, 1000);
							} else {
								this.querywayInfoindex = 1;
							}
						} else if (data == 2) {
							this.priceShow = true;
						} else if (data == 3) {
							this.$refs.uToast.show({
								title: "订单支付失败",
								type: "default",
								icon: false,
							});
						} else {
							this.$refs.uToast.show({
								title: res.data.message,
								type: "default",
								icon: false,
							});
						}
					} else {
						this.$refs.uToast.show({
							title: res.data.message,
							type: "default",
							icon: false,
						});
					}
				},
				fail: (res) => {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: res.data.error,
						type: "default",
						icon: false,
					});
				},
			});
		},
		// 重置
		// reset() {
		// 	this.carNumberIpt = '' //车牌号
		// 	this.nameIpt = '' //车主姓名
		// 	this.phoneIpt = '' //联系方式
		// },
	},
};
</script>

<style scoped>
.addCar input {
	border: 0;
}

.addCar {
	width: 100%;
	min-height: 100vh;
	background-color: #fff;
	overflow: hidden;
}

/* 列表 */

/* 内容 */
.OnlineRecharge-bottom {
	padding-top: 90rpx;
}

.OnlineRecharge-content-box {
	width: 100%;
	padding: 0 24rpx;
}

.OnlineRecharge-carName-phone {
	/* border-bottom: 2rpx solid rgba(230, 230, 230, 1); */
	padding: 25rpx 0;
	display: flex;
	flex-direction: row;
	align-items: center;
}

.OnlineRecharge-carName-renmb {
	border-bottom: 2rpx solid rgba(230, 230, 230, 1);
	font-size: 40rpx;
	font-weight: 600;
}

.OnlineRecharge-carName-tips {
	font-size: 28rpx;
	padding: 15rpx 0 10rpx;
}

.OnlineRecharge-carName-zc {
	font-size: 28rpx;
	color: rgba(0, 161, 244, 1);
}

.OnlineRecharge-input-one {
	width: 90% !important;
	display: inline-block;
	margin-bottom: 0 !important;
	padding: 0 !important;
	height: 44rpx !important;
	/* margin-left: 0.1rem; */
	color: #333333;
	font-size: 44rpx;
	text-align: center;
}

.addCar-phone {
	width: 238rpx;
	display: inline-block;
	font-size: 26rpx;
	color: rgba(102, 102, 102, 1);
	/* background: #000000; */
}

.Recharge-mode {
	padding-top: 50rpx;
}

.Recharge-mode-font {
	color: #999;
	font-size: 28rpx;
}

.Recharge-mode-top image {
	width: 36rpx;
	height: 36rpx;
	vertical-align: middle;
	margin-right: 10rpx;
}

/* 按钮 */
.addCar-reset-determine {
	margin-top: 167rpx;
	display: flex;
}

.addCar-reset-determine>view {
	width: 350rpx;
	margin: 0 auto;
	text-align: center;
	line-height: 70rpx;
	color: rgba(255, 255, 255, 1);
	font-size: 38rpx;
	border-radius: 28rpx 28rpx 28rpx 28rpx;
}

.addCar-reset {
	width: 159rpx;
	background: rgba(234, 197, 15, 1);
	text-align: center;
	margin-left: 170rpx;
}

.addCar-determine {
	background: rgba(0, 161, 244, 1);
	margin-left: 60rpx;
}

.addCar-phone-car {
	display: inline-block;
	width: 310rpx;
	height: 44rpx;
	line-height: 44rpx;
	/* border: 1px solid rgba(0, 0, 0, .2); */
	/* border-radius: 3px; */
	text-align: center;
	vertical-align: middle;
	font-size: 26rpx;
}

input::placeholder {
	color: rgba(102, 102, 102, 0.5);
}
</style>
